/**
 *
 */
package com.ean.backpack.validator;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ean.backpack.dto.UserDto;

/**
 * @author valentin
 *
 */
@Component("userValidator")
public class UserValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return UserDto.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		UserDto userDto = (UserDto) target;
		ValidationUtils.rejectIfEmpty(errors, "firstName",
				"createUser.firstName.notEmpty", "Firstname must not be empty.");

		ValidationUtils.rejectIfEmpty(errors, "lastName",
				"createUser.lastName.notEmpty", "Lastname must not be empty.");

		ValidationUtils.rejectIfEmpty(errors, "email",
				"createUser.email.notEmpty", "Email must not be empty.");

		ValidationUtils.rejectIfEmpty(errors, "password",
				"createUser.password.notEmpty", "Password must not be empty.");

		ValidationUtils.rejectIfEmpty(errors, "verifyPassword",
				"createUser.verifyPassword.notEmpty",
				"Verify password must not be empty.");

		String password = userDto.getPassword();
		String verifyPassword = userDto.getVerifyPassword();

		if (!StringUtils.equals(password, verifyPassword)) {
			errors.rejectValue("verifyPassword",
					"createUser.verifyPassword.match",
					"Verify password must match password.");
		}
	}

}
